package cn.edu.zjicm.wordsnet_d.download;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;

import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class JudgeNetwork {

	private boolean wifiConnected = false;// wifiConnected判断是否连接wifi

	private boolean mobileConnected = false;// wifiConnected判断是否连接使用流量

	private static JudgeNetwork mInstance;
	private Context context;

	public static JudgeNetwork getInstance(Context context) {
		mInstance = new JudgeNetwork(context);
		return mInstance;
	}

	public JudgeNetwork(Context context) {
		this.context = context;
		ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
		if (activeInfo != null && activeInfo.isConnected() && activeInfo.isAvailable()) {
			wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
			mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
		} else {
			wifiConnected = false;
			mobileConnected = false;
		}
	}

	public void refreshCurrentNetWork() {
		LogUtil.d("刷新网络", "刷新网络连接状态");
		ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
		if (activeInfo != null && activeInfo.isConnected() && activeInfo.isAvailable()) {
			wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
			mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
		} else {
			wifiConnected = false;
			mobileConnected = false;
		}
	}

	public boolean isWifiConnected() {
		return wifiConnected;
	}

	public void setWifiConnected(boolean wifiConnected) {
		this.wifiConnected = wifiConnected;
	}

	public boolean isMobileConnected() {
		return mobileConnected;
	}

	public void setMobileConnected(boolean mobileConnected) {
		this.mobileConnected = mobileConnected;
	}

//	public void ping() {
//
//		final int port = 80;
//		final String ip = "111.13.100.91";// 百度的ip
//		new Thread() {
//			public void run() {
//				Socket socket = new Socket();
//				try {
//					socket.connect(new InetSocketAddress(ip, port), 1 * 1000);
//					boolean result = socket.isConnected();
//					if (result) {
//						wifiConnected = true;
//					} else {
//						wifiConnected = false;
//					}
//					LogUtil.d("ping中,result=" + result);
//				} catch (IOException e) {
//					e.printStackTrace();
//				} finally {
//					try {
//						socket.close();
//					} catch (IOException e) {
//						e.printStackTrace();
//					}
//				}
//			};
//		}.start();
//
//	}
}
